package com.lazypeople.util;

import java.io.File;
import java.net.URI;
import java.net.URL;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FileUtils {
    private static final Logger logger = LoggerFactory.getLogger(FileUtils.class);

    public static String formatFileSize(long bytes) {
        if (bytes < 1024)
            return bytes + " B";
        int exp = (int) (Math.log(bytes) / Math.log(1024));
        String unit = "KMGTPE".charAt(exp - 1) + "B";
        return String.format("%.1f %s", bytes / Math.pow(1024, exp), unit);
    }

    public static String getFileNameFromUrl(String url) {
        try {
            URI uri = URI.create(url);
            String path = uri.getPath();
            String fileName = path.substring(path.lastIndexOf('/') + 1);
            if (fileName.isEmpty()) {
                fileName = "download_" + System.currentTimeMillis();
            }
            return fileName;
        } catch (Exception e) {
            return "download_" + System.currentTimeMillis();
        }
    }

    public static boolean isValidDirectory(String path) {
        if (path == null || path.trim().isEmpty()) {
            return false;
        }
        File directory = new File(path);
        return directory.exists() && directory.isDirectory() && directory.canWrite();
    }

    // 添加URL验证和文件类型判断
    public static boolean isValidUrl(String url) {
        if (url == null || url.isEmpty())
            return false;
        // 直接检查协议前缀，支持http/https/magnet
        return url.startsWith("http://") || url.startsWith("https://") || url.startsWith("magnet:");
    }

    public static boolean isSupportedFileType(String url) {
        if (url == null || url.isEmpty())
            return false;

        // 支持的文件类型列表
        String[] supportedExts = { "exe", "msi", "zip", "rar", "mp3", "mp4", "exe", "pdf", "doc", "docx", "xls", "xlsx",
                "ppt",
                "pptx" };
        String ext = getFileExtension(url).toLowerCase();

        for (String supported : supportedExts) {
            if (supported.equals(ext))
                return true;
        }
        return false;
    }

    private static String getFileExtension(String url) {
        try {
            // 处理URL参数
            int queryIndex = url.indexOf('?');
            if (queryIndex > 0)
                url = url.substring(0, queryIndex);

            // 提取文件扩展名
            int lastDotIndex = url.lastIndexOf('.');
            int lastSlashIndex = Math.max(url.lastIndexOf('/'), url.lastIndexOf('\\'));

            if (lastDotIndex > lastSlashIndex && lastDotIndex < url.length() - 1) {
                return url.substring(lastDotIndex + 1);
            }
        } catch (Exception e) {
            // 忽略解析错误
        }
        return "";
    }

    public static void main(String[] args) {
        String url = "https://download.ihsdus.cn/down/2024down/12/27/BaiduNetdisk_ydsd03_7.50.0.132.exe?timestamp=6877050b&auth_key=0b9da88baebe9004ef140b1350b0786e";
        logger.info("{}: {}", isValidUrl(url), isSupportedFileType(url));
    }
}